package container_usecase

import (
	"sync"

	"github.com/google/uuid"

	"octopus/internal/domain/entities"
	"octopus/internal/domain/interfaces"
)

// NewDefaultTaskManager 创建一个新的DefaultTaskManager实例
func NewDefaultTaskManager() interfaces.TaskManager {
	return &DefaultTaskManager{
		asks: &sync.Map{},
	}
}

// DefaultTaskManager 是 TaskManager 的默认实现
type DefaultTaskManager struct {
	asks    *sync.Map
	eventBus interfaces.EventBus
}

// CreateTask 创建新任务
func (tm *DefaultTaskManager) CreateTask(id string) *entities.Task {
	taskID := uuid.New().String()
	return &entities.Task{
		ID:        taskID,
		Type:      "restart",
		TargetID:  id,
		Status:    entities.TaskPending,
		CreatedAt: time.Now(),
		UpdatedAt: time.Now(),
	}
}

// UpdateTaskStatus 更新任务状态
func (tm *DefaultTaskManager) UpdateTaskStatus(task *entities.Task, status entities.TaskStatus) {
	task.Status = status
	task.UpdatedAt = time.Now()
	tm.tasks.Store(task.ID, task)
}

// NotifyTaskCompletion 通知任务完成
func (tm *DefaultTaskManager) NotifyTaskCompletion(task *entities.Task, notify func(task *entities.Task)) {
	if notify != nil {
		notify(task)
	}
	// 通过事件总线发布任务完成事件
	tm.eventBus.Publish(interfaces.TaskEventCompleted, &interfaces.TaskEventPayload{
		Task: task,
	})
}

// SetEventBus 设置事件总线
func (tm *DefaultTaskManager) SetEventBus(eventBus interfaces.EventBus) {
	tm.eventBus = eventBus
}